// 游戏配置
const config = {
    gridCols: 8,          // 游戏板的列数
    gridRows: 10,         // 游戏板的行数
    blockTypes: 5,        // 方块类型数量
    blockSize: 50,        // 方块大小
    matchMin: 3,          // 最小匹配数量
    gameTime: 60,         // 游戏时间（秒）
    fallingSpeed: 2,      // 方块下落速度
    newBlockInterval: 2000, // 新方块生成间隔（毫秒）
    horizontalMoveAmount: 50, // 水平移动距离
    gridOffset: {         // 网格偏移，确保方块对齐到网格
        x: 0,
        y: 0
    }
};

// 游戏状态
const gameState = {
    isRunning: false,
    timer: config.gameTime,
    player1: {
        score: 0,
        board: createEmptyBoard(),
        blocks: [],
        activeBlock: null
    },
    player2: {
        score: 0,
        board: createEmptyBoard(),
        blocks: [],
        activeBlock: null
    }
};

// 创建空的游戏板
function createEmptyBoard() {
    const board = [];
    for (let row = 0; row < config.gridRows; row++) {
        board[row] = [];
        for (let col = 0; col < config.gridCols; col++) {
            board[row][col] = null;
        }
    }
    return board;
}

// DOM 元素
const elements = {
    player1Board: document.querySelector('.player1-board'),
    player2Board: document.querySelector('.player2-board'),
    player1Score: document.querySelector('.player1-score'),
    player2Score: document.querySelector('.player2-score'),
    timer: document.querySelector('.timer'),
    startButton: document.getElementById('start-button'),
    restartButton: document.getElementById('restart-button'),
    gameOverModal: document.getElementById('game-over'),
    winnerText: document.getElementById('winner-text'),
    finalScore: document.getElementById('final-score'),
    playAgainButton: document.getElementById('play-again'),
    // 添加左右移动按钮元素
    player1LeftButton: document.getElementById('player1-left'),
    player1RightButton: document.getElementById('player1-right'),
    player2LeftButton: document.getElementById('player2-left'),
    player2RightButton: document.getElementById('player2-right')
};

// 初始化游戏
function initGame() {
    // 初始化SDK
    if (typeof window.CrazyGames !== 'undefined') {
        window.CrazyGames.SDK.init().then(() => {
            console.log("CrazyGames SDK 初始化成功");
            
            // 通知CrazyGames游戏开始加载
            window.CrazyGames.SDK.game.loadingStart();
            
            // 设置游戏板尺寸
            setupGameBoard(elements.player1Board);
            setupGameBoard(elements.player2Board);
            
            // 计算网格偏移，确保方块对齐到网格
            config.gridOffset.x = elements.player1Board.offsetLeft;
            config.gridOffset.y = elements.player1Board.offsetTop;
            
            // 添加事件监听器
            elements.startButton.addEventListener('click', startGame);
            elements.restartButton.addEventListener('click', resetGame);
            elements.playAgainButton.addEventListener('click', resetGame);
            
            // 添加左右移动按钮事件监听器
            elements.player1LeftButton.addEventListener('click', () => moveActiveBlock(gameState.player1, elements.player1Board, 'left'));
            elements.player1RightButton.addEventListener('click', () => moveActiveBlock(gameState.player1, elements.player1Board, 'right'));
            elements.player2LeftButton.addEventListener('click', () => moveActiveBlock(gameState.player2, elements.player2Board, 'left'));
            elements.player2RightButton.addEventListener('click', () => moveActiveBlock(gameState.player2, elements.player2Board, 'right'));
            
            // 通知CrazyGames游戏加载完成
            window.CrazyGames.SDK.game.loadingStop();
        }).catch(error => {
            console.error("CrazyGames SDK 初始化失败", error);
            // 继续初始化游戏，即使SDK加载失败
            setupGame();
        });
    } else {
        // SDK未加载，继续初始化游戏
        console.log("CrazyGames SDK 不可用，使用本地模式");
        setupGame();
    }
}

// 设置游戏（SDK初始化后或SDK加载失败时调用）
function setupGame() {
    // 设置游戏板尺寸
    setupGameBoard(elements.player1Board);
    setupGameBoard(elements.player2Board);
    
    // 计算网格偏移，确保方块对齐到网格
    config.gridOffset.x = elements.player1Board.offsetLeft;
    config.gridOffset.y = elements.player1Board.offsetTop;
    
    // 添加事件监听器
    elements.startButton.addEventListener('click', startGame);
    elements.restartButton.addEventListener('click', resetGame);
    elements.playAgainButton.addEventListener('click', resetGame);
    
    // 添加左右移动按钮事件监听器
    elements.player1LeftButton.addEventListener('click', () => moveActiveBlock(gameState.player1, elements.player1Board, 'left'));
    elements.player1RightButton.addEventListener('click', () => moveActiveBlock(gameState.player1, elements.player1Board, 'right'));
    elements.player2LeftButton.addEventListener('click', () => moveActiveBlock(gameState.player2, elements.player2Board, 'left'));
    elements.player2RightButton.addEventListener('click', () => moveActiveBlock(gameState.player2, elements.player2Board, 'right'));
}

// 设置游戏板
function setupGameBoard(boardElement) {
    boardElement.style.width = `${config.gridCols * config.blockSize}px`;
    boardElement.style.height = `${config.gridRows * config.blockSize}px`;
}

// 开始游戏
function startGame() {
    if (gameState.isRunning) return;
    
    gameState.isRunning = true;
    gameState.timer = config.gameTime;
    gameState.player1.score = 0;
    gameState.player2.score = 0;
    
    // 重置游戏板
    gameState.player1.board = createEmptyBoard();
    gameState.player2.board = createEmptyBoard();
    
    // 更新界面
    updateScores();
    updateTimer();
    
    // 隐藏开始按钮，显示重启按钮
    elements.startButton.style.display = 'none';
    elements.restartButton.style.display = 'block';
    
    // 开始游戏循环
    startGameLoop();
    
    // 定时生成新方块
    gameState.player1.blockInterval = setInterval(() => generateBlock(gameState.player1, elements.player1Board), config.newBlockInterval);
    gameState.player2.blockInterval = setInterval(() => generateBlock(gameState.player2, elements.player2Board), config.newBlockInterval);
    
    // 倒计时
    gameState.timerInterval = setInterval(updateTimer, 1000);
    
    // 通知CrazyGames SDK游戏已开始
    if (typeof window.CrazyGames !== 'undefined' && window.CrazyGames.SDK) {
        window.CrazyGames.SDK.game.gameplayStart();
    }
}

// 游戏循环
function startGameLoop() {
    gameState.animationId = requestAnimationFrame(gameLoop);
}

function gameLoop() {
    if (!gameState.isRunning) return;
    
    // 更新方块位置
    updateBlocks(gameState.player1, elements.player1Board);
    updateBlocks(gameState.player2, elements.player2Board);
    
    // 检查方块匹配
    checkMatches(gameState.player1, elements.player1Board);
    checkMatches(gameState.player2, elements.player2Board);
    
    gameState.animationId = requestAnimationFrame(gameLoop);
}

// 将位置转换为格子坐标
function posToGridCoords(x, y) {
    const col = Math.floor(x / config.blockSize);
    const row = Math.floor(y / config.blockSize);
    return { row, col };
}

// 将格子坐标转换为位置
function gridToPos(row, col) {
    return {
        x: col * config.blockSize,
        y: row * config.blockSize
    };
}

// 更新方块位置
function updateBlocks(player, boardElement) {
    const boardHeight = boardElement.offsetHeight;
    
    player.blocks.forEach(block => {
        // 如果方块已被消除，跳过
        if (block.isMatched) return;
        
        // 如果方块还在下落中
        if (!block.isStopped) {
            // 更新方块位置
            block.y += config.fallingSpeed;
            block.element.style.top = `${block.y}px`;
            
            // 检查是否到达底部或者下面有其他方块
            const { row, col } = posToGridCoords(block.x, block.y + config.blockSize);
            
            // 如果到达底部或者下面有方块则停止
            if (row >= config.gridRows || (row >= 0 && player.board[row][col])) {
                // 将方块对齐到网格
                const gridPos = gridToPos(row - 1, col);
                block.y = gridPos.y;
                block.element.style.top = `${block.y}px`;
                
                block.isStopped = true;
                block.row = row - 1;
                block.col = col;
                
                // 更新游戏板状态
                if (block.row >= 0 && block.row < config.gridRows && 
                    block.col >= 0 && block.col < config.gridCols) {
                    player.board[block.row][block.col] = block;
                }
                
                // 当前活动方块停止后，生成新方块
                if (player.activeBlock === block) {
                    player.activeBlock = null;
                }
            }
        }
    });
}

// 生成新方块
function generateBlock(player, boardElement) {
    if (!gameState.isRunning || player.activeBlock) return;
    
    const blockType = Math.floor(Math.random() * config.blockTypes) + 1;
    const col = Math.floor(Math.random() * config.gridCols);
    const x = col * config.blockSize;
    const y = 0;
    
    // 检查该列顶部是否已有方块，如果有则不生成
    if (player.board[0][col]) {
        return;
    }
    
    // 创建方块 DOM 元素
    const blockElement = document.createElement('div');
    blockElement.className = `block block-${blockType}`;
    blockElement.style.width = `${config.blockSize}px`;
    blockElement.style.height = `${config.blockSize}px`;
    blockElement.style.left = `${x}px`;
    blockElement.style.top = `${y}px`;
    
    // 创建方块对象
    const block = {
        type: blockType,
        x: x,
        y: y,
        row: 0,
        col: col,
        isStopped: false,
        isMatched: false,
        element: blockElement
    };
    
    // 将方块添加到游戏板
    boardElement.appendChild(blockElement);
    
    // 将方块添加到玩家的方块数组
    player.blocks.push(block);
    
    // 标记为活动方块
    player.activeBlock = block;
}

// 使用按钮移动活动方块
function moveActiveBlock(player, boardElement, direction) {
    if (!gameState.isRunning || !player.activeBlock || player.activeBlock.isStopped) {
        return;
    }
    
    const block = player.activeBlock;
    const moveDirection = direction === 'left' ? -1 : 1;
    
    // 计算新的列位置
    const newCol = block.col + moveDirection;
    
    // 检查新位置是否有效
    if (newCol < 0 || newCol >= config.gridCols) {
        return; // 超出边界
    }
    
    // 检查该位置是否已有方块
    for (let row = 0; row < config.gridRows; row++) {
        if (player.board[row][newCol] && player.board[row][newCol].y <= block.y + config.blockSize) {
            return; // 该位置已有方块
        }
    }
    
    // 更新方块位置
    block.col = newCol;
    block.x = block.col * config.blockSize;
    
    // 添加移动动画
    block.element.style.transition = 'left 0.15s ease-out';
    block.element.style.left = `${block.x}px`;
    
    // 移动后恢复正常过渡
    setTimeout(() => {
        block.element.style.transition = '';
    }, 150);
}

// 处理方块点击事件（保留但不再使用）
function handleBlockClick(block, player, boardElement) {
    if (!gameState.isRunning) return;
    
    // 点击已停止的方块，尝试消除
    if (block.isStopped) {
        tryMatch(block, player, boardElement);
    }
}

// 尝试匹配方块
function tryMatch(clickedBlock, player, boardElement) {
    // 查找相同类型的相邻方块
    const matches = findMatches(clickedBlock, player);
    
    // 如果匹配数量达到最小匹配数量
    if (matches.length >= config.matchMin) {
        // 创建特效
        createMatchEffect(matches, player, boardElement);
        
        // 移除匹配的方块，并更新游戏板状态
        matches.forEach(block => {
            block.isMatched = true;
            block.element.classList.add('block-explode');
            
            // 更新游戏板状态
            if (block.row >= 0 && block.col >= 0) {
                player.board[block.row][block.col] = null;
            }
            
            // 删除方块元素
            setTimeout(() => {
                if (block.element && block.element.parentNode) {
                    block.element.parentNode.removeChild(block.element);
                }
            }, 500);
        });
        
        // 更新玩家的方块数组
        player.blocks = player.blocks.filter(block => !block.isMatched);
        
        // 显示得分特效
        showScorePopup(matches, player, boardElement);
        
        // 增加玩家得分
        player.score += matches.length * 10;
        updateScores();
        
        // 应用重力效果 - 消除后让上方方块下落
        setTimeout(() => {
            applyGravity(player, boardElement);
        }, 500);
    }
}

// 应用重力效果，让方块下落填补空白
function applyGravity(player, boardElement) {
    // 遍历每一列
    for (let col = 0; col < config.gridCols; col++) {
        // 从底部向上遍历
        let emptyRow = -1;
        
        for (let row = config.gridRows - 1; row >= 0; row--) {
            // 如果找到空白位置
            if (!player.board[row][col] && emptyRow === -1) {
                emptyRow = row;
            }
            // 如果找到方块且下方有空白位置
            else if (player.board[row][col] && emptyRow !== -1) {
                const block = player.board[row][col];
                
                // 更新方块位置
                player.board[emptyRow][col] = block;
                player.board[row][col] = null;
                
                block.row = emptyRow;
                const newY = block.row * config.blockSize;
                
                // 动画移动方块
                block.element.style.transition = 'top 0.3s ease-in-out';
                block.element.style.top = `${newY}px`;
                block.y = newY;
                
                // 找到下一个空白位置
                emptyRow--;
            }
        }
    }
    
    // 恢复正常过渡效果
    setTimeout(() => {
        player.blocks.forEach(block => {
            if (!block.isMatched) {
                block.element.style.transition = '';
            }
        });
        
        // 移动后再次检查匹配
        checkMatches(player, boardElement);
    }, 300);
}

// 创建匹配特效
function createMatchEffect(matches, player, boardElement) {
    // 计算匹配区域的中心
    let centerX = 0;
    let centerY = 0;
    
    matches.forEach(block => {
        centerX += block.x + config.blockSize / 2;
        centerY += block.y + config.blockSize / 2;
        
        // 为每个匹配的方块添加发光效果
        block.element.classList.add('block-glow');
    });
    
    centerX /= matches.length;
    centerY /= matches.length;
    
    // 创建爆炸效果元素
    const effectElement = document.createElement('div');
    effectElement.className = 'match-effect';
    effectElement.style.left = `${centerX - 50}px`; // 50px是特效宽度的一半
    effectElement.style.top = `${centerY - 50}px`;  // 50px是特效高度的一半
    
    // 添加特效到游戏板
    boardElement.appendChild(effectElement);
    
    // 特效结束后移除
    setTimeout(() => {
        if (effectElement.parentNode) {
            effectElement.parentNode.removeChild(effectElement);
        }
    }, 500);
}

// 显示得分弹出效果
function showScorePopup(matches, player, boardElement) {
    // 计算匹配区域的中心
    let centerX = 0;
    let centerY = 0;
    
    matches.forEach(block => {
        centerX += block.x + config.blockSize / 2;
        centerY += block.y + config.blockSize / 2;
    });
    
    centerX /= matches.length;
    centerY /= matches.length;
    
    // 创建得分弹出元素
    const scoreElement = document.createElement('div');
    scoreElement.className = 'score-pop';
    scoreElement.textContent = `+${matches.length * 10}`;
    scoreElement.style.left = `${centerX - 20}px`; // 20px是文本宽度的估计一半
    scoreElement.style.top = `${centerY - 10}px`;
    
    // 添加到游戏板
    boardElement.appendChild(scoreElement);
    
    // 动画结束后移除
    setTimeout(() => {
        if (scoreElement.parentNode) {
            scoreElement.parentNode.removeChild(scoreElement);
        }
    }, 1000);
}

// 查找匹配
function findMatches(block, player) {
    const matches = [block];
    const visited = new Set();
    visited.add(block);
    
    findMatchesRecursive(block, player, matches, visited);
    
    return matches;
}

// 递归查找匹配
function findMatchesRecursive(block, player, matches, visited) {
    // 检查四个方向（上、右、下、左）
    const directions = [
        { row: -1, col: 0 }, // 上
        { row: 0, col: 1 },  // 右
        { row: 1, col: 0 },  // 下
        { row: 0, col: -1 }  // 左
    ];
    
    directions.forEach(dir => {
        const newRow = block.row + dir.row;
        const newCol = block.col + dir.col;
        
        // 检查新位置是否有效
        if (newRow >= 0 && newRow < config.gridRows && 
            newCol >= 0 && newCol < config.gridCols) {
            
            const adjacentBlock = player.board[newRow][newCol];
            
            // 如果有相同类型的方块并且未访问过
            if (adjacentBlock && 
                adjacentBlock.type === block.type && 
                !adjacentBlock.isMatched && 
                !visited.has(adjacentBlock)) {
                
                matches.push(adjacentBlock);
                visited.add(adjacentBlock);
                findMatchesRecursive(adjacentBlock, player, matches, visited);
            }
        }
    });
}

// 检查方块匹配
function checkMatches(player, boardElement) {
    // 遍历游戏板，查找可能的匹配
    for (let row = 0; row < config.gridRows; row++) {
        for (let col = 0; col < config.gridCols; col++) {
            const block = player.board[row][col];
            if (block && !block.isMatched && !block.checked) {
                block.checked = true;
                tryMatch(block, player, boardElement);
            }
        }
    }
}

// 更新得分
function updateScores() {
    elements.player1Score.textContent = gameState.player1.score;
    elements.player2Score.textContent = gameState.player2.score;
}

// 更新倒计时
function updateTimer() {
    if (gameState.timer <= 0) {
        endGame();
        return;
    }
    
    gameState.timer--;
    elements.timer.textContent = gameState.timer;
}

// 游戏结束
function endGame() {
    gameState.isRunning = false;
    
    // 清除定时器
    clearInterval(gameState.player1.blockInterval);
    clearInterval(gameState.player2.blockInterval);
    clearInterval(gameState.timerInterval);
    cancelAnimationFrame(gameState.animationId);
    
    // 显示游戏结束模态框
    const player1Score = gameState.player1.score;
    const player2Score = gameState.player2.score;
    
    if (player1Score > player2Score) {
        elements.winnerText.textContent = '玩家1获胜！';
        
        // 播放庆祝效果
        if (typeof window.CrazyGames !== 'undefined' && window.CrazyGames.SDK) {
            window.CrazyGames.SDK.game.happytime();
        }
    } else if (player2Score > player1Score) {
        elements.winnerText.textContent = '玩家2获胜！';
        
        // 播放庆祝效果
        if (typeof window.CrazyGames !== 'undefined' && window.CrazyGames.SDK) {
            window.CrazyGames.SDK.game.happytime();
        }
    } else {
        elements.winnerText.textContent = '平局！';
    }
    
    elements.finalScore.textContent = `玩家1: ${player1Score} 分 vs 玩家2: ${player2Score} 分`;
    elements.gameOverModal.style.display = 'flex';
    
    // 通知CrazyGames SDK游戏已结束
    if (typeof window.CrazyGames !== 'undefined' && window.CrazyGames.SDK) {
        window.CrazyGames.SDK.game.gameplayStop();
    }
    
    // 保存游戏得分（如果SDK可用）
    saveGameScore(player1Score, player2Score);
}

// 保存游戏得分到CrazyGames云端
function saveGameScore(player1Score, player2Score) {
    if (typeof window.CrazyGames !== 'undefined' && window.CrazyGames.SDK && window.CrazyGames.SDK.data) {
        const gameData = {
            lastGameScores: {
                player1: player1Score,
                player2: player2Score,
                timestamp: new Date().toISOString()
            },
            highScores: {
                player1: Math.max(player1Score, gameState.highScores?.player1 || 0),
                player2: Math.max(player2Score, gameState.highScores?.player2 || 0)
            }
        };
        
        // 保存到CrazyGames云端
        window.CrazyGames.SDK.data.set('gameData', gameData)
            .then(() => {
                console.log('游戏数据已保存到CrazyGames云端');
                gameState.highScores = gameData.highScores;
            })
            .catch(error => {
                console.error('保存游戏数据失败:', error);
            });
    }
}

// 加载游戏数据
function loadGameData() {
    if (typeof window.CrazyGames !== 'undefined' && window.CrazyGames.SDK && window.CrazyGames.SDK.data) {
        window.CrazyGames.SDK.data.get('gameData')
            .then(data => {
                if (data) {
                    console.log('从CrazyGames云端加载游戏数据:', data);
                    gameState.highScores = data.highScores || { player1: 0, player2: 0 };
                }
            })
            .catch(error => {
                console.error('加载游戏数据失败:', error);
            });
    }
}

// 显示中间广告
function showMidgameAd() {
    if (typeof window.CrazyGames !== 'undefined' && window.CrazyGames.SDK && window.CrazyGames.SDK.ad) {
        // 通知游戏已停止
        window.CrazyGames.SDK.game.gameplayStop();
        
        // 请求中间广告
        window.CrazyGames.SDK.ad.requestAd('midgame')
            .then(ad => {
                ad.onFinish(() => {
                    // 广告结束后继续游戏
                    console.log('中间广告播放完成，继续游戏');
                    window.CrazyGames.SDK.game.gameplayStart();
                });
                // 显示广告
                ad.show();
            })
            .catch(error => {
                console.error('请求中间广告失败:', error);
                // 即使广告加载失败，也继续游戏
                window.CrazyGames.SDK.game.gameplayStart();
            });
    }
}

// 重置游戏
function resetGame() {
    // 清除所有方块
    elements.player1Board.innerHTML = '';
    elements.player2Board.innerHTML = '';
    
    // 重置游戏状态
    gameState.player1.blocks = [];
    gameState.player2.blocks = [];
    
    // 隐藏游戏结束模态框
    elements.gameOverModal.style.display = 'none';
    
    // 在游戏重启前显示中间广告
    if (Math.random() < 0.5) { // 50%的概率显示广告
        showMidgameAd();
    } else {
        // 直接开始新游戏
        startGame();
    }
}

// 页面加载完成后初始化游戏
window.addEventListener('load', function() {
    // 初始化游戏
    initGame();
    
    // 加载游戏数据
    loadGameData();
}); 